<template>
  <Modal v-model="visible"
         title="添加部门"
         @on-cancel="closeModal"
         footer-hide
         :width="620">
    <Form ref="form" :model="form" :rules="rules"
          :label-width="100">
      <FormItem label="部门名" prop="name">
        <Input v-model="form.name" placeholder="请输入部门名"></Input>
      </FormItem>
      <FormItem label="上级部门" prop="parentIds">
        <Cascader v-model="form.parentIds" placeholder="请选择上级部门"
                  :data="departments" change-on-select></Cascader>
      </FormItem>
      <FormItem>
        <Button type="primary" :loading="submitting" @click="submit">提交</Button>
      </FormItem>
    </Form>
  </Modal>
</template>

<script>
import { departmentTree, createDepartment } from '../../../../apis/system/department';
import SystemUtil from '../../../../utils/systemUtil';

export default {
  name: 'create',
  data() {
    return {
      visible: false,
      form: {
        name: undefined,
        parentIds: []
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名', trigger: 'blur' }
        ]
      },
      departments: [],
      submitting: false
    };
  },
  methods: {
    openModal() {
      this.visible = true;
      this.initDepartments();
    },
    initDepartments() {
      departmentTree(undefined, (responseData) => {
        this.departments = SystemUtil.getDepartments(responseData);
      });
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitting = true;

          const parentId = this.form.parentIds && this.form.parentIds.length > 0
            ? this.form.parentIds[this.form.parentIds.length - 1] : undefined;
          createDepartment({
            name: this.form.name,
            parentId
          }, () => {
            this.submitting = false;

            this.$Message.success('保存成功');
            this.closeModal();
            this.$refs.form.resetFields();
            this.$emit('success');
          }, () => {
            this.submitting = false;
          });
        }
      });
    },
    closeModal() {
      this.visible = false;
    },
  }
};
</script>

<style scoped>

</style>
